package com.sishu.njrtsdms.security.handle;


import com.sishu.njrtsdms.constant.Constants;
import com.sishu.njrtsdms.domain.core.AjaxResult;
import com.sishu.njrtsdms.domain.core.LoginUser;
import com.sishu.njrtsdms.manager.AsyncManager;
import com.sishu.njrtsdms.manager.factory.AsyncFactory;
import com.sishu.njrtsdms.service.system.TokenService;
import com.sishu.njrtsdms.utils.ServletUtils;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


/**
 * 自定义退出处理类 返回成功
 *
 * @author jtc
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    private final TokenService tokenService;

    public LogoutSuccessHandlerImpl(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (ObjUtil.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.INSTANCE.recordLoginInfo(userName, Constants.LOGOUT,
                    "退出成功"));
        }
        ServletUtils.renderString(response, JSONUtil.toJsonStr(AjaxResult.success("退出成功")));
    }
}
